import 'package:biometrics/components/common.dart';
import 'package:biometrics/components/controller.dart';
import 'package:biometrics/components/method.dart';
import 'package:biometrics/facedetect_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: IntentHandler(),
    );
  }
}

class IntentHandler extends StatefulWidget {
  const IntentHandler({super.key});

  @override
  IntentHandlerState createState() => IntentHandlerState();
}

class IntentHandlerState extends State<IntentHandler> {
  String? action;
  static Controller? controller;
  Widget? floatingActionButton;
  Method method = Method();
  int? deleteId;

  Widget get modeIcon => method.isSafety == true
      ? const Icon(Icons.health_and_safety)
      : const Icon(Icons.warning);
  static Future<SharedPreferences> get prefs => SharedPreferences.getInstance();

  @override
  void initState() {
    super.initState();
    prefs.then((pref) {
      var isSafety = pref.getBool("isSafety") ?? false;
      method.switchMode(flag: isSafety);
      setState(() {});
    });
    _getIntentAction();
  }

  Future<void> _getIntentAction() async {
    try {
      final Map<String, dynamic>? resultMap = await method.getIntentAction();
      if (resultMap == null) return;

      action = resultMap['action'];
      LOG.info << "action: $action" << resultMap;
      int faceId = 0;
      if (resultMap['face_id'] != null) {
        faceId = int.tryParse(resultMap['face_id'] as String)!;
      }
      switch (action) {
        case 'com.example.record_face':
          controller = Controller(ControllerType.detect, faceId: faceId);
          break;
        case 'com.example.recognize_face':
          controller = Controller(ControllerType.recognize);
          break;
        case 'com.example.verify_face':
          controller = Controller(ControllerType.recognize, faceId: faceId);
          break;
        default:
          controller = Controller(ControllerType.detect);
          break;
      }
      controller!.callWhenTaskComplete((v) {
        floatingActionButton = FloatingActionButton(
          onPressed: () {
            method.setResultAndClose(v == null ? 0 : 1, v.toString());
          },
          child: const Icon(Icons.check),
        );
        setState(() {});
      });
      setState(() {});
    } on PlatformException catch (e) {
      print("获取Intent失败: ${e.message}");
    }
  }

  @override
  Widget build(BuildContext context) {
    LOG.info << "action: $action";
    if (controller == null) {
      return Scaffold(body: Center(child: Text('未知操作: $action')));
    }

    switch (action) {
      case 'com.example.record_face':
        return _buildScreen('人脸录入');
      case 'com.example.recognize_face':
        return _buildScreen('人脸比对');
      case 'com.example.verify_face':
        return _buildScreen('人脸鉴别');
      default:
        return _buildScreen('测试界面');
    }
  }

  Widget _buildScreen(String screen) {
    return Scaffold(
      appBar: AppBar(title: Text('$screen界面')),
      body: Center(
        child: controller == null
            ? Container()
            : Facedetectview(
                controller: controller!,
              ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          // 返回结果并关闭App
          if (floatingActionButton != null) floatingActionButton!,

          // 删除人脸特征
          if (screen == '人脸鉴别' &&
              controller != null &&
              controller!.faceId != null) ...[
            const SizedBox(height: 20),
            FloatingActionButton(
              onPressed: () async {
                controller!.removeTip(deleteId);
                int? ret = await method.clearUserFaceFeatures(0);
                if (ret == 0) {
                  deleteId = controller!.addTip('删除成功');
                  Future.delayed(const Duration(seconds: 1)).then((v) {
                    method.setResultAndClose(1, '100');
                  });
                } else {}
              },
              child: const Icon(Icons.clear),
            )
          ],

          if (method.isSafety != null) ...[
            // 切换模式
            const SizedBox(height: 20),
            FloatingActionButton(
              onPressed: () {
                method.switchMode();
                setState(() {});
              },
              child: modeIcon,
            ),
          ],

          // 读取所有特征值
          const SizedBox(height: 20),
          FloatingActionButton(
            onPressed: () async {
              controller!.addTip('读取所有特征值中');
              String ret = await method.listall();
              if (ret != '') {
                controller!.addTip('读取特征值成功: $ret', level: TipLevel.success);
              } else {
                controller!.addTip('读取失败', level: TipLevel.error);
              }
            },
            child: const Icon(Icons.search),
          ),
        ],
      ),
    );
  }
}
